<?php
namespace app\admin\model;
use think\Model;
use app\admin\model\Users;
class Messages extends Model
{
	public static $mails;
	public static $tousers = [];
	public static function Notice($touser,$title,$content='',$type=1,$cc=0){ //0不抄送，1抄送给所有的客服，2抄送给所有的admin，3抄送给所有的admin&service
		self::$mails = [];
		$data['create_time'] = time();
		$data['type'] = $type;
		self::$tousers[] = $data['touser'] = $touser;
		$data['content'] = $content;
		$data['title'] = $title;
		if($touser > 0){
			db('Messages')->insert($data);
			self::$mails[] = array('title'=>$data['title'],'content'=>$data['content'],'create_time'=>time(),'email'=>Users::getEmail($touser));
		}
		self::cc($cc,$data);
		self::addEmail();
 	}
	public static function getTypeAttr($type){
		$typeList = array(1=>lang('Open process reminder'),2=>lang('Line deletion reminder'),3=>lang('Line expiration reminder'),4=>lang('Broadband adjustment reminder'),5=>lang('Renewal reminder'));
		return isset($typeList[$type]) ? $typeList[$type] : '';
	}
	public function getUrlAttr($value){
		return U('message/view',['message_id'=>$value]);
	}
	/*抄送*/
	public static function cc($cc,$data){
		switch ($cc) {
			case 1: //不抄送，1抄送给所有的客服
				# code...
			    self::cc_service($data);
				break;
			case 2: //抄送给所有的admin
				self::cc_admin($data);
				break;
			case 3: //抄送给所有的admin&service
				self::cc_service($data);
				self::cc_admin($data);
				break;
			default:
				# code...
				break;
		}
		return '';
	}
	/*抄送给客服*/
	public static function cc_service($data){
		$services = db('users')->where('group_id',4)->where('is_open',1)->select();
		if($services){
			$base = [];
			$mails = array('title'=>$data['title'],'content'=>$data['content'],'create_time'=>time());
			$emails = [];
			foreach($services as $v){
				if(in_array($v['admin_id'], self::$tousers)){
					continue;
				}
				self::$tousers[] = $data['touser'] = $v['admin_id'];
				$base[] = $data;
				if(is_email($v['email'])){
					$emails[] = $v['email'];
				}
			}
			$mails['email'] = implode(",", $emails);
			self::$mails[] = $mails;
			
			return db('Messages')->insertAll($base);
		}
		return false;
	}
	/*抄送给管理员*/
	public static function cc_admin($data){
		$admins = db('users')->where('group_id',1)->where('is_open',1)->select();
		if($admins){
			$base = [];
			$mails = array('title'=>$data['title'],'content'=>$data['content'],'create_time'=>time());
			$emails = [];
			foreach($admins as $v){
				if(in_array($v['admin_id'], self::$tousers)){
					continue;
				}
				self::$tousers[] = $data['touser'] = $v['admin_id'];
				$base[] = $data;
				if(is_email($v['email'])){
					$emails[] = $v['email'];
				}
			}
			$mails['email'] = implode(",", $emails);
			self::$mails[] = $mails;
			return db('Messages')->insertAll($base);
		}
		return false;
	}
	public static function addEmail(){
		if(count(self::$mails) > 0){
			return db('emails')->insertAll(self::$mails);
		}
		
	}
}